//
//  CZOauthViewController.swift
//  git
//
//  Created by 徐 鹏超 on 16/4/9.
//  Copyright © 2016年 徐 鹏飞. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class CZOauthViewController: UIViewController,UIWebViewDelegate {

    let webView :UIWebView = UIWebView()
    
    override func loadView() {
        view = webView
        
        // 设置代理
        webView.delegate = self
        
        setupNav()
    }
    
    
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
        
    }
    //MARK:--按钮点击方法
    func dismiss(){
        dismissViewControllerAnimated(true) { () -> Void in
            //
        }
        
    }
    func auto(){
        // 自动填充只在作为一个 JS与 WebView交互的一个方式, 大家记住 stringByEvaluatingJavaScriptFromString 可以和js交互,针对js的东西可以不用了解
        let js = "document.getElementById(\"userId\").value = \"itcast123456@hotmail.com\";document.getElementById(\"passwd\").value = \"itcast123456\""
        
        webView.stringByEvaluatingJavaScriptFromString(js)
        
        printLog("自动填充")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor() 
        
        // 设置webView的显示的内容
        // 拼接一个URL
        // 1.0 拼接url
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(AppURL)"
        
        
        let url = NSURL(string: urlString)
        
        if let url = url {
            let request = NSURLRequest(URL: url)
            
            webView.loadRequest(request)
        }
    
    
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
   
//    optional public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool

}

extension CZOauthViewController{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        // if let判断获取 绝对路径
        if let absoluteString = request.URL?.absoluteString{
            if absoluteString .hasPrefix(AppURL){
                
                printLog(absoluteString)
                
                printLog(request.URL?.query)
                
                guard let code = request.URL?.query else{
                    return true
                }
                let subStr = code.substringFromIndex("code=".endIndex)
                
                printLog(subStr)
                
                //发送一个网络请求来获取一个token
                getToken(subStr,success:{() -> () in
                    printLog("归档成功")
                    
                    // 跳转到欢迎页面
                    // 通知中心发送通知
                    NSNotificationCenter.defaultCenter().postNotificationName(kNotificationChangeController, object: self)
                    
                    
                    },failed:{() -> () in
                        printLog("归档失败")
                    }
                )
            }
        }
        return true
    }
}

extension CZOauthViewController{
    
    func getToken(code:String, success:() -> (),failed:() -> ()){
        //创建一个afn实例
        let afn = AFHTTPSessionManager()
        //设置afn contentType
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        let params = ["client_id":AppKey,
            "client_secret":AppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":AppURL
        ]
        
        afn.POST("https://api.weibo.com/oauth2/access_token", parameters: params, progress: nil, success: { (_, JSON) -> Void in
            printLog(JSON)
            // 先判断可选项,并且需要转换成 字典
            guard let json = JSON as?[String:NSObject] else{
                return
            }
            let userModel = CZUserModel(dic: json)
            
            self.getUserInfo(userModel,success:success,failed:failed)
            
            }) { (_, error) -> Void in
                printLog(error)
        }
    }
}

extension CZOauthViewController{
    
    func getUserInfo(model : CZUserModel,success:() -> (),failed:() -> () ){
        // 1.实例化afn
        let afn = AFHTTPSessionManager()
        //2.拼接参数
        guard let token = model.access_token,uid = model.uid else{
            return
        }
        
        let params = ["access_token":token,
            "uid":uid
        ]
        afn.GET("https://api.weibo.com/2/users/show.json", parameters: params, progress: nil, success: { (_, JSON) -> Void in
            printLog(JSON)
            
            guard let json = JSON as? [String:NSObject] else{
                return
            }
            let name = json["name"]
            
            let newName = name as? String
            
            model.name = newName
            //
            model.avatar_large = json["avatar_large"] as? String
            
            
            printLog(model.avatar_large)
            
            NSKeyedArchiver.archiveRootObject(model, toFile: filePath)
            
            printLog(filePath)
            
            success()
            
            }) { (_, error) -> Void in
                printLog(error)
                
                failed()
        }
        
        
        }
    
    
    
    
}




